package com.ndood.gateway.base.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * http://web.chacuo.net/netrsakeypair
 * https://blog.csdn.net/hcmdy/article/details/51996994 PKCS8
 * https://www.cnblogs.com/blogzhangwei/p/10145167.html PKCS12
 */
public class RSAUtil {
	static Logger LOG = LoggerFactory.getLogger(RSAUtil.class);

	private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; // 签名算法
	private static final String KEY_ALGORITHM = "RSA"; // 加密算法RSA
	
	/**
     * 字节数据转字符串专用集合
     */
    private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	/**
	 * 随机生成RSA密钥对
	 */
	public static String[] generateKeyPair() {
		// 随机生成密钥对
		KeyPairGenerator keyPairGen = null;
		try {
			keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}
		// 初始化密钥对生成器，密钥大小为96-1024位
		keyPairGen.initialize(1024, new SecureRandom());
		// 生成一个密钥对，保存在keyPair中
		KeyPair keyPair = keyPairGen.generateKeyPair();
		// 得到私钥
		String publicKeyString = Base64.encodeBase64String(keyPair.getPublic().getEncoded());
		// 得到公钥
		String privateKeyString = Base64.encodeBase64String(keyPair.getPrivate().getEncoded());
		return new String[] { publicKeyString, privateKeyString };
	}
	
	/**
     * 随机生成RSA密钥对 
	 * @param filePath
	 */
    public static void genKeyPair(String filePath) {
        // KeyPairGenerator类用于生成公钥和私钥对，基于RSA算法生成对象
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 初始化密钥对生成器，密钥大小为96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一个密钥对，保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        try {
            // 得到公钥字符串
            String publicKeyString = Base64.encodeBase64String(keyPair.getPublic().getEncoded());
            // 得到私钥字符串
            String privateKeyString = Base64.encodeBase64String(keyPair.getPrivate().getEncoded());
            // 将密钥对写入到文件
            FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
            FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
            BufferedWriter pubbw = new BufferedWriter(pubfw);
            BufferedWriter pribw = new BufferedWriter(prifw);
            pubbw.write(publicKeyString);
            pribw.write(privateKeyString);
            pubbw.flush();
            pubbw.close();
            pubfw.close();
            pribw.flush();
            pribw.close();
            prifw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    
    /**
     * 从文件中输入流中加载公钥
     *
     * @param in
     *            公钥输入流
     * @throws Exception
     *             加载公钥时产生的异常
     */
    public static String loadPublicKeyByFile(String path) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new FileReader(path
                    + "/publicKey.keystore"));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            br.close();
            return sb.toString();
        } catch (IOException e) {
            throw new Exception("公钥数据流读取错误");
        } catch (NullPointerException e) {
            throw new Exception("公钥输入流为空");
        }
    }
 
    /**
     * 从字符串中加载公钥
     *
     * @param publicKeyStr
     *            公钥数据字符串
     * @throws Exception
     *             加载公钥时产生的异常
     */
    public static PublicKey loadPublicKeyByStr(String publicKeyStr)
            throws Exception {
        try {
            byte[] buffer = Base64.decodeBase64(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return (PublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }
 
    /**
     * 从文件中加载私钥
     *
     * @param keyFileName
     *            私钥文件名
     * @return 是否成功
     * @throws Exception
     */
    public static String loadPrivateKeyByFile(String path) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new FileReader(path
                    + "/privateKey.keystore"));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            br.close();
            return sb.toString();
        } catch (IOException e) {
            throw new Exception("私钥数据读取错误");
        } catch (NullPointerException e) {
            throw new Exception("私钥输入流为空");
        }
    }
 
    public static PrivateKey loadPrivateKeyByStr(String privateKeyStr)
            throws Exception {
        try {
            byte[] buffer = Base64.decodeBase64(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            return (PrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法");
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }
 
    /**
     * 公钥加密过程
     *
     * @param publicKey
     *            公钥
     * @param plainTextData
     *            明文数据
     * @return
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static String encrypt(String publicKey, String plainTextData)
            throws Exception {
        if (publicKey == null) {
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher = null;
		
        try {
        	PublicKey publicK = KeyFactory.getInstance(KEY_ALGORITHM)
    				.generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(publicKey)));
            // 使用默认RSA
            cipher = Cipher.getInstance(KEY_ALGORITHM);
            // cipher= Cipher.getInstance(KEY_ALGORITHM, new BouncyCastleProvider());
            cipher.init(Cipher.ENCRYPT_MODE, publicK);
            byte[] output = cipher.doFinal(plainTextData.getBytes(Charset.forName("UTF-8")));
            return new String(Base64.encodeBase64(output),"UTF-8");
            
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }
 
    /**
     * 私钥加密过程
     *
     * @param privateKey
     *            私钥
     * @param plainTextData
     *            明文数据
     * @return
     * @throws Exception
     *             加密过程中的异常信息
     */
    @Deprecated
    public static byte[] encrypt(PrivateKey privateKey, byte[] plainTextData)
            throws Exception {
        if (privateKey == null) {
            throw new Exception("加密私钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance(KEY_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(plainTextData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }
 
    /**
     * 私钥解密过程
     *
     * @param privateKey
     *            私钥
     * @param cipherData
     *            密文数据
     * @return 明文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public static String decrypt(String privateKey,String cipherData)
            throws Exception {
        if (privateKey == null) {
            throw new Exception("解密私钥为空, 请设置");
        }
        Cipher cipher = null;
        
        try {
			PrivateKey privateK = KeyFactory.getInstance(KEY_ALGORITHM)
					.generatePrivate(new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey)));
            // 使用默认RSA
            cipher = Cipher.getInstance(KEY_ALGORITHM);
            // cipher= Cipher.getInstance(KEY_ALGORITHM, new BouncyCastleProvider());
            cipher.init(Cipher.DECRYPT_MODE, privateK);
            byte[] output = cipher.doFinal(Base64.decodeBase64(cipherData));
            return new String(output, "UTF-8");
            
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }
 
    /**
     * 公钥解密过程
     *
     * @param publicKey
     *            公钥
     * @param cipherData
     *            密文数据
     * @return 明文
     * @throws Exception
     *             解密过程中的异常信息
     */
    @Deprecated
    public static byte[] decrypt(PublicKey publicKey, byte[] cipherData)
            throws Exception {
        if (publicKey == null) {
            throw new Exception("解密公钥为空, 请设置");
        }
        Cipher cipher = null;
        try {
            // 使用默认RSA
            cipher = Cipher.getInstance(KEY_ALGORITHM);
            // cipher= Cipher.getInstance(KEY_ALGORITHM, new BouncyCastleProvider());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(cipherData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }
 
    /**
     * 字节数据转十六进制字符串
     *
     * @param data
     *            输入数据
     * @return 十六进制内容
     */
    public static String byteArrayToString(byte[] data) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
            // 取出字节的低四位 作为索引得到相应的十六进制标识符
            stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
            if (i < data.length - 1) {
                stringBuilder.append(' ');
            }
        }
        return stringBuilder.toString();
    }

    /**
	 * 公钥验签
	 */
	public static boolean verify(Map<String,Object> map, String sign, String publicKey) {
		String text = genenrateSignSrc(map); // 获取签名源串
		try {
			Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
			PublicKey key = KeyFactory.getInstance(KEY_ALGORITHM)
					.generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(publicKey)));
			signature.initVerify(key);
			signature.update(text.getBytes());
			return signature.verify(Base64.decodeBase64(sign));
		} catch (Exception e) {
			LOG.error("验签失败:text={},sign={}", text, sign, e);
		}
		return false;
	}
    
	/**
	 * 公钥验签
	 */
	public static boolean verify(String text, String sign, String publicKey) {
		try {
			Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
			PublicKey key = KeyFactory.getInstance(KEY_ALGORITHM)
					.generatePublic(new X509EncodedKeySpec(Base64.decodeBase64(publicKey)));
			signature.initVerify(key);
			signature.update(text.getBytes());
			return signature.verify(Base64.decodeBase64(sign));
		} catch (Exception e) {
			LOG.error("验签失败:text={},sign={}", text, sign, e);
		}
		return false;
	}

	/**
	 * 签名字符串
	 *
	 * @param text
	 *            需要签名的字符串
	 * @param privateKey
	 *            私钥(BASE64编码)
	 * @return 签名结果(BASE64编码)
	 */
	public static String sign(String text, String privateKey) {
		byte[] keyBytes = Base64.decodeBase64(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
			Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
			signature.initSign(privateK);
			signature.update(text.getBytes());
			byte[] result = signature.sign();
			return Base64.encodeBase64String(result);
		} catch (Exception e) {
			LOG.error("签名失败,text={}", text, e);
		}
		return null;
	}
	
	/**
	 * 签名字符串
	 *
	 * @param text
	 *            需要签名的字符串
	 * @param privateKey
	 *            私钥(BASE64编码)
	 * @return 签名结果(BASE64编码)
	 */
	public static String sign(Map<String,Object> map, String privateKey) {
		String text = genenrateSignSrc(map);
		byte[] keyBytes = Base64.decodeBase64(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
			Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
			signature.initSign(privateK);
			signature.update(text.getBytes());
			byte[] result = signature.sign();
			return Base64.encodeBase64String(result);
		} catch (Exception e) {
			LOG.error("签名失败,text={}", text, e);
		}
		return null;
	}
	
	public static void main(String[] args) {
		// 1 测试RSA加密解密
		String[] keyPair1 = RSAUtil.generateKeyPair();
		
		try {
			String cipherData = RSAUtil.encrypt(keyPair1[0], "test");
			System.out.println(new String(cipherData));
			
			String decrypt = RSAUtil.decrypt(keyPair1[1], cipherData);
			System.out.println(new String(decrypt));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// 2 测试RSA签名验签
		String sign = RSAUtil.sign("TTTT", keyPair1[1]);
		System.out.println(sign);
		
		boolean verify = RSAUtil.verify("TTTT", sign, keyPair1[0]);
		System.out.println(verify);
	}

	/**
	 * 获取签名字符串
	 */
	/**
	 * 构建签名原文
	 * 
	 * @param signFilds 参数列表
	 * @param param 参数与值的jsonbject
	 * @return
	 */
	public static String genenrateSignSrc(Map<String,Object> map) {
		List<String> signFields = new ArrayList<String>(map.keySet());
		
		Collections.sort(signFields);
 
		StringBuffer signSrc = new StringBuffer("");
		for (int i=0; i< signFields.size(); i++) {
			String field = signFields.get(i);
			Object value = map.get(field);
			if("sign".equals(field)) {
				continue;
			}
			if(value==null) {
				continue;
			}
			if(StringUtils.isEmpty(value.toString())) {
				continue;
			}
			signSrc.append(field);
			signSrc.append("=");
			signSrc.append(map.get(field));
			// 最后一个元素后面不加&
			if (i < (signFields.size() - 1)) {
				signSrc.append("&");
			}
		}
		return signSrc.toString();
	}


}
